package jwtRequest

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"week_one/client/common/global"
)

type ClaimsToken struct {
	Id   uint
	Name string
	jwt.StandardClaims
}

// 生成token
func AuthToken(id uint, name string) (string, error) {
	jwtClient := NewJwtClient([]byte(global.ClientConfig.JwtConf.SigningKey))
	return jwtClient.CreateToken(id, name)
}

// 解析token
func ParseToken() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.GetHeader("token")
		if token == "" {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"msg": "请登录",
			})
			return
		}
		jwtClient := NewJwtClient([]byte(global.ClientConfig.JwtConf.SigningKey))
		claims := jwtClient.ParseToken(token)
		if claims.ExpiresAt < time.Now().Unix() {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"msg": "token已经过期",
			})
			return
		}
		ctx.Set("claims", claims)
	}
}
